package com.sky.controller.user;

import cn.dev33.satoken.annotation.SaCheckLogin;
import com.alibaba.dashscope.app.ApplicationResult;
import com.sky.result.Result;
import com.sky.service.AIService;
import io.reactivex.Flowable;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.io.IOException;

/**
 * AI对话接口
 */
@RestController
@RequestMapping("/user/ai")
@Slf4j
public class UserAIController {

    @Autowired
    private AIService aiService;

    /**
     * 与AI进行对话（流式输出）
     * @param prompt 用户输入的问题
     * @return SSE连接，用于流式输出
     */
    @SaCheckLogin
    @PostMapping("/chat")
    public SseEmitter chat(@RequestParam String prompt) {
        log.info("与AI进行对话（流式输出）:{}", prompt);
        SseEmitter emitter = new SseEmitter();
        
        // 创建一个新线程来处理流式响应
        new Thread(() -> {
            try {
                Flowable<ApplicationResult> resultFlowable = aiService.chat(prompt);
                
                resultFlowable.blockingForEach(result -> {
                    try {
                        // 发送数据给客户端
                        emitter.send(result.getOutput().getText());
                    } catch (IOException e) {
                        log.error("发送AI响应数据失败", e);
                        emitter.completeWithError(e);
                    }
                });
                
                // 完成发送
                emitter.complete();
            } catch (Exception e) {
                log.error("AI对话过程发生错误", e);
                emitter.completeWithError(e);
            }
        }).start();
        
        return emitter;
    }
} 